﻿using BarcodeDelay.bean;
using BarcodeDelay.FrameDecoder;
using BarcodeDelay.logHelp;
using BarcodeDelay.utility;
using JTParcrelHelper.bean;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BarcodeDelay.business
{
    public class InboundSignMessageHelper
    {
        private StreamWriter swb = null;
        FileStream bFile = null;
        ArrayList m_arListDepBarcodes = new ArrayList();
        public event Action DoneHttpResponse;
        public event Action GotInterceptBarcode;
    
        private string m_strCurBarcode = "";
        ArrayList m_arListBarcodes = new ArrayList();
        ArrayList arListArbitrationBarcodes = new ArrayList();
        private bool isInProcess = false;

        private bool isCuiTypeWhenAssign = true;
        private DateTime dtLastInter = System.DateTime.Now;
        Hashtable htInterNoRoadMap = new Hashtable();


        public Hashtable htInterCeptFaile = new Hashtable();
        public event Action SignSucessBarcode;
        public event Action SignFailedBarcode;
        Hashtable htAutoTaskAssigned = new Hashtable();
        private static InboundSignMessageHelper instance;
        public static InboundSignMessageHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new InboundSignMessageHelper();
                }
                return instance;
            }
        }
        private Thread fThreadDep = null;
        public void BeginAnalyThread(ArrayList  arListBarcodes, string anayType)
        {
            try
            {
                m_arListBarcodes.Clear();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    fThreadDep.Abort();
                    System.Threading.Thread.Sleep(50);
                }
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    while (fThreadDep.ThreadState != ThreadState.Aborted)
                    {
                        //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                        Thread.Sleep(100);
                    }
                }

                m_arListBarcodes = arListBarcodes;

                fThreadDep = new Thread(new ParameterizedThreadStart(handleAllBarcodes));
                fThreadDep.Start((object)arListBarcodes);


            }
            catch (Exception ex)
            {

            }
        }

        public void handleInprocessTransfer(string billcode,out string outMsg)
        {
            outMsg = "";
            try
            {
                //查询是否有待审核
                string queryUrl = "https://jmsgw.jtexpress.com.cn/operatingplatform/rebackTransferExpress/problemExpressPage";
                JObject jObj = new JObject();
                jObj["current"] = 1;
                jObj["size"] = 20;
                jObj["auditNetworkId"] = Convert.ToInt32(StoParams.Instance.register_networkId);
                jObj["applyTimeFrom"] = System.DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + " " + "00:00:00"; 
                jObj["applyTimeTo"] = System.DateTime.Now.ToString("yyyy-MM-dd") + " " + "23:59:59"; 
                jObj["status"] = 1;
                jObj["countryId"] = "1";
                JArray jarr = new JArray();
                jarr.Add(billcode);
                jObj["waybillIds"] = jarr;
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string res = HttpClient.HttpUtil.Instance.PostCommon(queryUrl, postData, "returnAndForwardMaintain");

                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(res);
                JObject dataObj = (JObject)jsonObjRes["data"];

                JArray records = (JArray)dataObj["records"];
                if (records.Count == 0)
                {
                    return;
                }
                string codeStr = "";
                bool isFind = false;
                for (int i = 0; i < records.Count; i++)
                {
                    JObject jsonObjFirst = (JObject)records[0];
                    JToken waybillToken = jsonObjFirst["waybillNo"];
                    if(waybillToken.ToString()== billcode)
                    {
                        JToken statusName = jsonObjFirst["statusName"];
                        JToken applyTypeName = jsonObjFirst["applyTypeName"];
                        if(statusName.ToString()== "待审核"&& applyTypeName.ToString()== "修改收件地址")
                        {
                            isFind = true;
                            break;
                        }
                    }
                }
                if(isFind)
                {
                    //撤销改地址
                    queryUrl = "https://jmsgw.jtexpress.com.cn/operatingplatform/rebackTransferExpress/revocation";
                    jObj = new JObject();
                    
                    jObj["reason"] = "";
                    jObj["countryId"] = "1";
                    jarr = new JArray();
                    jarr.Add(billcode);
                    jObj["waybillIds"] = jarr;
                    postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                    res = HttpClient.HttpUtil.Instance.PostCommon(queryUrl, postData, "interceptQueryBackNew");

                    jsonObjRes = (JObject)JsonConvert.DeserializeObject(res);
                    JToken sucToken = (JToken)jsonObjRes["succ"];
                    if(sucToken.ToString().ToLower()=="true")
                    {
                        outMsg = "撤销改地址成功";
                    }

                }
            }
            catch(Exception ex)
            {

            }
        }

        public void handleAllBarcodes(object arListDepBarcodes)
        {
            try
            {
                StoParams.Instance.addCommentParcels = 0;
                string outmsg = "";
                StoParams.Instance.curParces++;
                isInProcess = true;

                ArrayList countArr = (ArrayList)arListDepBarcodes;
                int totalCount = countArr.Count;
                StoParams.Instance.totalParcels = totalCount;
                foreach (ParcelBean parcelBean in (ArrayList)arListDepBarcodes)
                {

                    StoParams.Instance.curParces++;
                    string strBarcode = parcelBean.wayBill;       
                    if(strBarcode.Length<10)
                    {
                        continue;
                    }

                    string pickName = "";
                    string curBarcodeToken = "";
                    string orderSource = "";
                    string curSiteToken = "";
                    string customerName = "";

                    /*if (!UtilityHelp.Instance.resetToken(strBarcode,out pickName,out orderSource,out curSiteToken,out customerName))
                    {
                        string lanshouSite = "";
                        if (curSiteToken=="")
                        {
                            StoParams.Instance.htResWechat[strBarcode] = " 发件网点 " + pickName + " 登录失效";
                            continue;                          
                                     
                        }

                        ArrayList arListAllGXTask3 = new ArrayList();
                        string httpRes3 = "";
                        ArrayList arListRoadMap3 = JTDelayHelper.Instance.getRoadMap(strBarcode, out httpRes3, arListAllGXTask3);
                        lanshouSite = JTDelayHelper.Instance.getLanShouSite(arListRoadMap3);

                        if (lanshouSite!= pickName&& lanshouSite.Length>2)
                        {
                            pickName = lanshouSite;
                        }
                        bool findSite = false;
                        foreach (DictionaryEntry de in StoParams.Instance.htDifferentSiteBarcodeInfo)
                        {
                            if(de.Key.ToString()== pickName)
                            {
                                findSite = true;
                                break;
                            }
                        }
                        if(!findSite)
                        {
                            StoParams.Instance.htResWechat[strBarcode] = " 发件网点 " + pickName + " 非我司单号  无法处理";
                            continue;
                        }
                            
                     }*/
                    parcelBean.customerName = customerName;   

                    if (totalCount > 10)
                    {
                        System.Threading.Thread.Sleep(1600);
                    }
                    else
                    {
                        TimeSpan ts = System.DateTime.Now - dtLastInter;
                        if(ts.TotalSeconds<1.5)
                        {
                            System.Threading.Thread.Sleep(1000);
                        }
                        
                    }

                    
                    string outTransferMsg = "";

                    string outMsg = "";
                    string lastUpdateTime = "";


                    m_strCurBarcode = strBarcode;
                    StoParams.Instance.interResMsg = "";
                    ArrayList arListAllGXTask = new ArrayList();
                    string httpRes = "";
                    ArrayList arListRoadMap = JTDelayHelper.Instance.getRoadMap(strBarcode, out httpRes, arListAllGXTask);


                    string lanshouTime = JTDelayHelper.Instance.getLanShouTime(arListRoadMap);
                    parcelBean.lanshouTime = lanshouTime;

                    if (arListRoadMap.Count == 0)
                    {
                        StoParams.Instance.htResWechat[strBarcode] = "快件未发出无法登记，后续跟踪";
                        parcelBean.replyType = "进港登记无物流";
                        continue;
                    }

                    FrameDecoderManager.Instance.lastSendRes = System.DateTime.Now;
                    if(DoneHttpResponse!=null)
                    {
                        DoneHttpResponse();
                    }
                    
                    string problemType = "";
                    outMsg = "";
                    string commentType = "";
                    string strInterCeptSiteCode = "";



                    string phoneNumber = "";
                    if (parcelBean.phoneNumList.Count > 0)
                    {
                        phoneNumber = parcelBean.phoneNumList[parcelBean.phoneNumList.Count-1];
                    }

                    string siteName = "";
                    //JTDelayHelper.Instance.parseInterceptBarcode(arListRoadMap, out commentType, out strInterCeptSiteCode,out siteName);
                    string tmpLv = "";

                    JTDelayHelper.Instance.parseInboundManualBarcode(strBarcode, out strInterCeptSiteCode, out siteName);
                    string fullLeaveMsg = "";
                    string signMsg = "";
                    StoParams.Instance.currentBarcode = m_strCurBarcode;
                    if (signProblemParcel(m_strCurBarcode, out signMsg, strInterCeptSiteCode, siteName, StoParams.Instance.inboundTemplete, commentType))
                    {
                        StoParams.Instance.resMsg = siteName+" 登记成功";
                        StoParams.Instance.addCommentParcels++;
                        StoParams.Instance.curDelayBarcode = strBarcode;
                        SignSucessBarcode();
                        
                    }
                    else
                    {
                        StoParams.Instance.resMsg = siteName + " 登记失败 "+ signMsg;
                        StoParams.Instance.curFailedBarcode = strBarcode;
                        SignFailedBarcode();
                    }



                    StoParams.Instance.interResMsg = m_strCurBarcode + "\r\n" + StoParams.Instance.interResMsg;
                    if(DoneHttpResponse!=null)
                    {
                        DoneHttpResponse();
                    }
                    
                    Thread.Sleep(200);

                    StoParams.Instance.interResMsg = outMsg;
          
                }               
                
            }
            catch(Exception ex)
            {
                isInProcess = false;
                StoParams.Instance.resMsg = "请求失败，请重新登录";
                if(DoneHttpResponse!=null)
                {
                    DoneHttpResponse();
                }
                
            }
            isInProcess = false;
        }

        private bool interceptProblemParcel(ArrayList arListRoadMap, string strCurBarcode, out string msg)
        {
            msg = "";
            bool res = false;
            try
            {
                string strUrl = "https://jmsgw.jtexpress.com.cn/operatingplatform/interceptTurnBack/batchQueryRegister";
                JObject jObj = new JObject();

                JArray jarry = new JArray();
                jObj["countryId"] = "1";
                jObj["applyTypeCode"] = 3;
                jarry.Add(strCurBarcode);
                jObj["waybillNos"] = jarry;
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string resMsg = HttpClient.HttpUtil.Instance.PostCommon(strUrl, postData, "interceptQueryBackNew");
                if(resMsg.Contains("运单不存在"))
                {
                    msg = "请求失败，运单不存在";
                    return false;
                }
                if (!resMsg.Contains("请求成功"))
                {
                    msg = "请求失败";
                    //return false;
                }
                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                JArray records = (JArray)jsonObjRes["data"];
                JObject firstObj = (JObject)records[0];
                JToken remark = firstObj["remark"];

                JToken enteringFlag= firstObj["enteringFlag"];

                JToken senderMobilePhone = firstObj["senderMobilePhone"];
                if (enteringFlag.ToString()!="1")
                {
                    if (remark!=null&&remark.ToString().Length > 2)
                    {
                        msg = "拦截失败:" + remark.ToString();
                        return false;
                    }
                    else
                    {
                        msg = "拦截失败" ;
                        return false;
                    }
                }
                

                if (records.Count == 0)
                {
                    //msg = strCurBarcode + " 查询失败,跳过拦截环节";
                    //return false;
                }
                strUrl = "https://jmsgw.jtexpress.com.cn/operatingplatform/interceptTurnBack/addRegister";
                jObj = new JObject();
                jObj["countryId"] = "1";
                jObj["applyTypeCode"] = 3;
                jObj["waybillNo"] = strCurBarcode;
                jObj["newReceiverMobilePhone"] = senderMobilePhone.ToString();
                
                postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                

              
                resMsg = HttpClient.HttpUtil.Instance.PostCommon(strUrl, postData, "interceptQueryBackNew");
                if (!resMsg.Contains("请求成功"))
                {
                    logHelp.LogHelper.Instance.writeLog("拦截失败，返回信息：" + resMsg + " token=" + MemberInfo.Instance.token);
                    jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                    JToken msgToke = jsonObjRes["msg"];
                    msg = "拦截失败:" + msgToke.ToString();
                    return false;
                }
                else
                {
                    msg = "拦截成功";
                    res = true;
                    return true;
                }
                //jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
            }
            catch (Exception ex)
            {

            }


            return res;
        }



        private bool interceptProblemParcel_Single(ArrayList arListRoadMap, string strCurBarcode, out string msg)
        {
            msg = "";
            bool res = false;
            try
            {
                string strUrl = "https://jmsgw.jtexpress.com.cn/operatingplatform/rebackTransferExpress/findByWaybillNo?waybillNo="+ strCurBarcode + "&applyTypeCode=3";
                JObject jObj = new JObject();
                JArray jarry = new JArray();
                jObj["current"] = 1;
                jObj["size"] = 20;
                jObj["countryId"] = "1";
                jObj["applyTypeCode"] = 3;
                jarry.Add(strCurBarcode);
                jObj["waybillIds"] = jarry;
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);

                string resMsg = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData, "GET", "returnAndForwardMaintainAddSite");
                JObject jsonObj = (JObject)JsonConvert.DeserializeObject(resMsg);
                JToken status = (JToken)jsonObj["code"];

                if (!resMsg.Contains("请求成功"))
                {
                    msg = "请求失败";
                    //return false;
                }
                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                JObject records = (JObject)jsonObjRes["data"];
                JToken receiverProvinceId = records["receiverProvinceId"];
                JToken receiverProvinceName = records["receiverProvinceName"];

                JToken receiverCityId = records["receiverCityId"];
                JToken receiverCityName = records["receiverCityName"];

                JToken receiverAreaId = records["receiverAreaId"];
                JToken receiverAreaName = records["receiverAreaName"];
                

                JObject newSenderProvince = JTDelayHelperNew.Instance.packageArea(receiverProvinceId, receiverProvinceName);
                JObject newSenderCity = JTDelayHelperNew.Instance.packageArea(receiverCityId, receiverCityName);
                JObject newSenderArea = JTDelayHelperNew.Instance.packageArea(receiverAreaId, receiverAreaName);


                JObject newRecProvince = JTDelayHelperNew.Instance.packageArea(records["senderProvinceId"], records["senderProvinceName"]);
                JObject newRecCity = JTDelayHelperNew.Instance.packageArea(records["senderCityId"], records["senderCityName"]);
                JObject newRecArea = JTDelayHelperNew.Instance.packageArea(records["senderAreaId"], records["senderAreaName"]);

                records["newReceiverArea"] = newRecArea;
                records["newReceiverAreaId"] = newRecArea["id"];
                records["newReceiverAreaName"] = newRecArea["cnName"];

                records["newReceiverCity"] = newRecCity;
                records["newReceiverCityId"] = records["senderCityId"];
                records["newReceiverCityName"] = records["senderCityName"];
                records["newReceiverDetailedAddress"] = records["senderDetailedAddress"];
                records["newReceiverMobilePhone"] = records["senderMobilePhone"];


                records["newSenderProvince"] = newSenderProvince;
                records["newSenderProvinceId"] = records["receiverProvinceId"];
                records["newSenderProvinceName"] = records["receiverProvinceName"];

                records["newSenderCityId"] = records["receiverCityId"];
                records["newSenderCityName"] = records["receiverCityName"];


                records["newSenderAreaId"] = newSenderArea["id"];
                records["newSenderAreaName"] = newSenderArea["cnName"];

                records["newSenderCity"] = newSenderCity;
                records["newSenderArea"] = newSenderArea;


                records["countryId"] = "1";

                records["newSenderName"] = records["receiverName"];
                records["newSenderMobilePhone"] = records["receiverMobilePhone"];
                records["newSenderTelphone"] = records["receiverTelphone"];

                records["newSenderTownship"] = records["receiverTownship"];
                records["newSenderStreet"] = records["receiverStreet"];
                records["newSenderDetailedAddress"] = records["receiverDetailedAddress"];


                records["newReceiverProvince"] = newRecProvince;
                records["newReceiverCity"] = newRecCity;
                records["newReceiverArea"] = newRecArea;

                records["newReceiverProvinceId"] = records["senderProvinceId"];
                records["newReceiverProvinceName"] = records["senderProvinceName"];


                records["newPackageChargeWeight"] = records["packageChargeWeight"];

                records["applyTypeCode"] =3;



                strUrl = "https://jmsgw.jtexpress.com.cn/operatingplatform/rebackTransferExpress/add";
      
                postData = Newtonsoft.Json.JsonConvert.SerializeObject(records);
                resMsg = HttpClient.HttpUtil.Instance.PostCommon(strUrl, postData, "returnAndForwardMaintainAddSite");
                if (!resMsg.Contains("请求成功"))
                {
                    logHelp.LogHelper.Instance.writeLog("拦截失败，返回信息：" + resMsg + " token=" + MemberInfo.Instance.token);
                    jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                    JToken msgToke = jsonObjRes["msg"];
                    msg = "拦截失败:" + msgToke.ToString();
                    return false;
                }
                else
                {
                    msg = "拦截成功";
                    res = true;
                    return true;
                }
                //jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
            }
            catch (Exception ex)
            {

            }


            return res;
        }

        private bool interceptProblemParcel_old(ArrayList arListRoadMap, string strCurBarcode,out string msg)
        {
            msg = "";
            bool res = false;
            try
            {
                string strUrl = "https://jmsgw.jtexpress.com.cn/operatingplatform/rebackTransferExpress/getBatchRebackWaybill";
                JObject jObj = new JObject();

                JArray jarry = new JArray();
                jObj["current"] = 1;
                jObj["size"] = 20;
                jObj["countryId"] = "1";
                jObj["applyTypeCode"] = 3;
                jarry.Add(strCurBarcode);
                jObj["waybillIds"] = jarry;
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string resMsg = HttpClient.HttpUtil.Instance.PostCommon(strUrl, postData, "returnAndForwardMaintain");
                if (!resMsg.Contains("请求成功"))
                {
                    msg = "请求失败";
                    //return false;
                }
                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                JArray records = (JArray)jsonObjRes["data"];
                if (records.Count == 0)
                {
                    //msg = strCurBarcode + " 查询失败,跳过拦截环节";
                    //return false;
                }
                strUrl = "https://jmsgw.jtexpress.com.cn/operatingplatform/rebackTransferExpress/addRebackExpress";
                jObj = new JObject();
                jObj["countryId"] = "1";
                jObj["applyTypeCode"] = 3;
                jObj["waybillNo"] = strCurBarcode;
                postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                resMsg = HttpClient.HttpUtil.Instance.PostCommon(strUrl, postData, "returnAndForwardMaintain");
                if (!resMsg.Contains("请求成功"))
                {
                    logHelp.LogHelper.Instance.writeLog("拦截失败，返回信息："+ resMsg+" token="+ MemberInfo.Instance.token);
                    jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                    JToken msgToke = jsonObjRes["msg"];
                    msg = "拦截失败:"+ msgToke.ToString();
                    return false;
                }
                else
                {
                    msg = "拦截成功";
                    res = true;
                    return true;
                }
                //jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
            }
            catch (Exception ex)
            {

            }


            return res;
        }

        public bool signProblemParcel(string strCurBarcode,out string msg,string strInterCeptSiteCode,string siteName,string fullLeaveMsg,string commentType)
        {                     
            if(fullLeaveMsg.Length>100)
            {
                fullLeaveMsg = fullLeaveMsg.Substring(0, 100);
            }

            //if (StoParams.Instance.register_site.Contains("茂名"))
            {
                fullLeaveMsg = fullLeaveMsg.Replace("，", ",");
                fullLeaveMsg = fullLeaveMsg.Replace("延误仲裁查件", "");
                fullLeaveMsg = fullLeaveMsg.Replace("遗失仲裁查件", "");
                fullLeaveMsg = fullLeaveMsg.Replace("破损仲裁查件", "");
                fullLeaveMsg = fullLeaveMsg.Trim().TrimStart(',');
            }
            msg = "";
            bool res = false;
            try
            {
                string strQueryUrl = "https://jmsgw.jtexpress.com.cn/servicequality/problemPiece/queryOperationType?waybillNo=" + strCurBarcode;
                JObject jObj = new JObject();
                JArray jarry = new JArray();

                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string resMsg = HttpClient.HttpUtil.Instance.QueryCommon(strQueryUrl, postData, "GET", "batchProblem");
                if (!resMsg.Contains("请求成功"))
                {
                    msg = "登记失败";
                    return false;
                }

                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);   
                JArray records = (JArray)jsonObjRes["data"];
                if (records.Count == 0)
                {
                    msg = "登记失败";
                    return false;
                }
                string codeStr = "";
                for (int i=0;i< records.Count;i++)
                {
                    JObject jsonObjFirst = (JObject)records[0];
                    JToken codeToken = jsonObjFirst["code"];
                    codeStr = codeToken.ToString();
                    if(codeStr=="4")
                    {
                        break;
                    }
                }
                codeStr = "1";

                strQueryUrl = "https://jmsgw.jtexpress.com.cn/basicdata/sysAbnormalPiece/select?size=999999&levelType=1&operatorType=" + codeStr;
                jObj = new JObject();
                jarry = new JArray();

                postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                resMsg = HttpClient.HttpUtil.Instance.QueryCommon(strQueryUrl, postData, "GET", "batchProblem");
                if (!resMsg.Contains("请求成功"))
                {
                    msg = "登记失败";
                    return false;
                }

                jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                JObject dataObj = (JObject)jsonObjRes["data"];
                records = (JArray)dataObj["records"];
                if (records.Count == 0)
                {
                    msg = "登记失败";
                    return false;
                }
    
                


                //string strUrl = "https://jmsgw.jtexpress.com.cn/basicdata/network/select/all?current=1&size=100&name=" + strInterCeptSiteCode + "&typeIds%5B0%5D=336&queryLevel=3";
                string strUrl = "https://jmsgw.jtexpress.com.cn/servicequality/problemPiece/getPageByName?current=1&size=10&queryLevel=3&name="  + siteName;
                jObj = new JObject();
                jarry = new JArray();

                postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                resMsg = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData, "GET", "batchProblem");
                if(!resMsg.Contains("请求成功"))
                {
                    msg = "登记失败";
                    return false;
                }
                jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                JObject jsonObjData = (JObject)jsonObjRes["data"];
                records = (JArray)jsonObjData["records"];
                if(records.Count==0)
                {
                    msg = "网点编码："+ strInterCeptSiteCode+" 不存在,跳过登记环节";
                    return false;
                }
                string signStieCode = "";
                int receiveNetworkId = 0;
                for (int i=0;i< records.Count;i++)
                {
                    JObject json = (JObject)records[i];
                    JToken code = json["code"];
                    JToken id = json["id"];
                    if (code!=null)
                    {
                        if(code.ToString()== strInterCeptSiteCode|| id.ToString()== strInterCeptSiteCode)
                        {
                            signStieCode = code.ToString();
                            if(id!=null)
                            {
                                receiveNetworkId = Convert.ToInt32(id);
                            }
                            break;
                        }
                    }
                }
                if(signStieCode==""|| receiveNetworkId==0)
                {
                    msg = "网点编码：" + strInterCeptSiteCode + " 不存在,跳过登记环节";
                    return false;
                }


                string firstLevelTypeName = StoParams.Instance.firstProblemBean.name;
                int probleTypeSubjectId = StoParams.Instance.firstProblemBean.id;
                int probleTypeSubjectId2 = StoParams.Instance.secondProblemBean.id;
                string problemTypeSubjectCode = StoParams.Instance.firstProblemBean.code;

                string secondLevelTypeCode = StoParams.Instance.secondProblemBean.code;
                int secondLevelTypeId = StoParams.Instance.secondProblemBean.id;
                string secondLevelTypeName = StoParams.Instance.secondProblemBean.name;

                /*if(commentType.Contains("派件")&& StoParams.Instance.isCuiTypeWhenAssign)
                {
                    firstLevelTypeName = "催件";
                    probleTypeSubjectId = 100123;
                    probleTypeSubjectId2 = 100124;
                    problemTypeSubjectCode = "50";
                    secondLevelTypeCode = "50a";
                    secondLevelTypeId = 100124;
                    secondLevelTypeName = "催件a";
                }*/
                bool resSign = signType(out msg, firstLevelTypeName, probleTypeSubjectId, probleTypeSubjectId2,
                                        problemTypeSubjectCode, secondLevelTypeCode, secondLevelTypeId, receiveNetworkId, strCurBarcode, fullLeaveMsg, secondLevelTypeName);
                if(resSign)
                {
                    return true;
                }

                return resSign;



            }
            catch(Exception ex)
            {

            }

            
         
            return res;
        }

        private bool signType(out string msg,string firstLevelTypeName, int probleTypeSubjectId, int probleTypeSubjectId2,
                                        string problemTypeSubjectCode,string secondLevelTypeCode, int secondLevelTypeId,int receiveNetworkId,string strCurBarcode
            ,string fullLeaveMsg,string secondLevelTypeName)
        {
            if(fullLeaveMsg.Length>100)
            {
                fullLeaveMsg = "此件麻烦尽快退回，客户已拒收，商家急催，避免客户投诉，如已遗失，麻烦联系我司处理理赔";
            }
            msg = "";
            bool res = false;
            try
            {
                string strUrl = "https://jmsgw.jtexpress.com.cn/servicequality/problemPiece/registration";
                string routerName = "batchProblem";
                JObject jObj = new JObject();
                jObj["countryId"] = "1";
                jObj["defaultKnow"] = null;
                jObj["firstLevelTypeName"] = firstLevelTypeName;
                jObj["knowNetwork"] = "";
                jObj["paths"] = "";
                jObj["probleTypeId"] = 1;
                jObj["probleTypeSubjectId"] = probleTypeSubjectId;
                jObj["probleTypeSubjectId2"] = probleTypeSubjectId2;
                jObj["problemPieceId"] = "";
                jObj["problemTypeSubjectCode"] = problemTypeSubjectCode;
                jObj["receiveNetworkId"] = receiveNetworkId;
                jObj["replyContent"] = "";
                //jObj["probleDescription"] = "此件麻烦尽快退回，客户已拒收，商家急催，避免客户投诉，如已遗失，麻烦联系我司处理理赔 ";
                jObj["probleDescription"] = fullLeaveMsg;
                jObj["replyContentImg"] = new JArray();
                jObj["replyStatus"] = 0;
                jObj["secondLevelTypeCode"] = secondLevelTypeCode;
                jObj["secondLevelTypeId"] = probleTypeSubjectId2;
                jObj["secondLevelTypeName"] = secondLevelTypeName;
                jObj["uploadDataProp"] = "";
                jObj["waybillNo"] = strCurBarcode;
                jObj["knowNetwork"] = "";
         
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string token = "";
                foreach(DictionaryEntry de in StoParams.Instance.htTokenSign)
                {
                    token = de.Key.ToString();
                }
                string resMsg = HttpClient.HttpUtil.Instance.PostCommonByToken(strUrl, postData, routerName, token);
                if (!resMsg.Contains("请求成功"))
                {
                    JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                    JToken msgToke = jsonObjRes["msg"];

                    msg = "登记失败:" + msgToke.ToString();
                    return false;
                }
                else
                {
                    res = true;
                    msg = "登记成功";
                    return true;
                }
            }
            catch(Exception ex)
            {

            }
            return res;
        }

        private bool addComment(string recvPhone, string strBarCode,string commentType,string addr,string leavemsg,string wechat,out string  errorMsg,out string outLeaveMsg,bool isYishi=false)
        {

            outLeaveMsg = leavemsg;
            bool ret = false;
            errorMsg = "";
            try
            {
                string strUrl = "https://jmsgw.jtexpress.com.cn/servicequality/leaveMessage/getReceiveNetwork?waybillNo=" + strBarCode.Trim();
                JObject jObj = new JObject();
                JArray jarry = new JArray();
                jarry.Add(strBarCode);

                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string res = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData, "GET", "integratedQuery");
                /*if (!res.Contains("请求成功"))
                {
                    if (res.Contains("msg"))
                    {
                        JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(res);
                        JToken msgToken = jsonObjRes["msg"];
                        StoParams.Instance.interResMsg = msgToken.ToString();
                    }
                    else
                    {
                        StoParams.Instance.interResMsg = res.ToString();
                    }
                    //QueryMessageRes.Invoke();
                    return ret;
                }*/
                string msg = "";
                ArrayList arListRoadMap = new ArrayList();
                ArrayList arListRoadGX = new ArrayList();
                arListRoadMap = JTDelayHelperNew.Instance.getRoadMap(strBarCode.Trim(), out msg, arListRoadGX);
                SiteBean siteBean = UtilityHelp.Instance.getFirstSite(res, arListRoadMap);
                if (siteBean.siteCode == "")
                {
                    siteBean = UtilityHelp.Instance.getBeanSite(arListRoadMap);
                    if(siteBean.siteName == StoParams.Instance.register_site)
                    {
                        errorMsg = "留言忽略自身网点";
                    }
                }
                //SiteBean siteBean = UtilityHelp.Instance.getLastSite(res);

                if (siteBean.siteCode == ""&& siteBean.siteId=="")
                {
                    return ret;
                }

                string partNumber = "";
                if (recvPhone!="")
                {
                    string phone = recvPhone;
                    if (phone.Contains("-"))
                    {
                        partNumber = phone.Substring(phone.IndexOf('-') + 1);
                        phone = phone.Substring(0, phone.IndexOf('-'));

                    }
                    recvPhone = phone;


                }

                if (siteBean.siteCode == "" && siteBean.siteId != "")
                {
                    try
                    {
                        strUrl = "https://jmsgw.jtexpress.com.cn/operatingplatform/networkInfo/getNetworkDetailInfoById?networkId=" + siteBean.siteId.Trim();
                        jObj = new JObject();
                        jarry = new JArray();
                        jarry.Add(strBarCode);

                        postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                        res = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData, "GET", "trackingExpress");
                        if (res.Contains("请求成功"))
                        {
                            if (res.Contains("data"))
                            {
                                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(res);

                                JObject jsonObjData = (JObject)jsonObjRes["data"]; ;
                                JToken networkCode = jsonObjData["networkCode"];
                                siteBean.siteCode = networkCode.ToString();

                            }

                        }
                    }
                    catch(Exception ex)
                    {

                    }
                    
                }
                if (StoParams.Instance.register_site.Contains(siteBean.siteName.Trim())
                    || siteBean.siteName.Trim().Contains(StoParams.Instance.register_site))
                {
                    errorMsg = "已退回揽收网点";
                    return ret;
                }
                jObj["waybillNo"] = strBarCode.Trim();
                jObj["receiveNetworkId"] = siteBean.siteId.Trim();
                jObj["fileUrl"] = "";
                jObj["receiveNetworkName"] = siteBean.siteName.Trim();
                jObj["receiveNetworkCode"] = siteBean.siteCode.Trim();
                jObj["countryId"] = "1";
                //jObj["leaveMessageType"] = 5;

                jObj["receiverPhone"] = recvPhone;
                jObj["leaveMessageType"] = 5;
                leavemsg = leavemsg.Replace("延误仲裁", "遗失仲裁");

                if (StoParams.Instance.register_site.Contains("阳江") || StoParams.Instance.register_site.Contains("太和") || StoParams.Instance.register_site.Contains("邓岗") || StoParams.Instance.register_site.Contains("江门")|| StoParams.Instance.register_site.Contains("水洲"))
                {
                    leavemsg = leavemsg.Replace("延误", "遗失");

                    if (recvPhone != "" || (StoParams.Instance.register_site.Contains("邓岗") || StoParams.Instance.register_site.Contains("江门") || StoParams.Instance.register_site.Contains("太和") || StoParams.Instance.register_site.Contains("水洲")))
                    {
                        SecondTypeBean secondTypeBean = new SecondTypeBean();
                        UtilityHelp.Instance.parseSecondTypeYishiAndDelay(arListRoadMap, "遗失仲裁", secondTypeBean, StoParams.Instance.register_site);
                        if (secondTypeBean.code != "")
                        {
                            jObj["leaveMessageType"] = 3;
                            jObj["secondTypeName"] = secondTypeBean.name;
                            jObj["secondTypeCode"] = secondTypeBean.code;
                            
                        }
                    }
                }

                if(isYishi)
                {
                    leavemsg = leavemsg.Replace("延误", "遗失");

                    if (recvPhone != "")
                    {
                        SecondTypeBean secondTypeBean = new SecondTypeBean();
                        UtilityHelp.Instance.parseSecondTypeYishiAndDelay(arListRoadMap, "遗失仲裁", secondTypeBean, StoParams.Instance.register_site);
                        if (secondTypeBean.code != "")
                        {
                            jObj["leaveMessageType"] = 3;
                            jObj["secondTypeName"] = secondTypeBean.name;
                            jObj["secondTypeCode"] = secondTypeBean.code;

                        }
                    }
                }

            



                //string tmplete = "此件已退款，商家急催要求尽快退回";
                /*if (wechat==""|| wechat.Contains("wechat"))
                {
                    wechat = MemberInfo.Instance.templeteAssign;
                }*/
                string tmplete = leavemsg+" "+addr;
                if(wechat.Length>3)
                {
                    tmplete = tmplete + " 协商加微信" + wechat;
                }
                outLeaveMsg = tmplete;
               /*if(commentType=="")
               {
                   commentType = "中转";
               }
               if(commentType.Contains("中转"))
               {
                   tmplete = MemberInfo.Instance.templeteTransfer;
               }
               else if (commentType.Contains("派件"))
               {
                   tmplete = MemberInfo.Instance.templeteAssign;
               }
               else if (commentType.Contains("签收"))
               {
                   tmplete = MemberInfo.Instance.templeteQS;
               }*/
               jObj["replyContent"] = tmplete.Trim().TrimEnd(',');
                //string postUrl = "https://jmsgw.jtexpress.com.cn/servicequality/leaveMessage/add";
                string postUrl = "https://jmsgw.jtexpress.com.cn/operatingplatform/messageBoard/add";
                postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);

            
                string messge = HttpClient.HttpUtil.Instance.addLeaveMessage(postUrl, postData);
                if (messge.Contains("成功"))
                {
                    ret = true;
                    StoParams.Instance.interResMsg = "留言成功-"+ siteBean.siteName;
                }
                else
                {
                    JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(messge);
                    JToken msgToken = jsonObjRes["msg"];
                    string msgStr = "";
                    if(msgToken!=null)
                    {
                        msgStr = msgToken.ToString();

                        logHelp.LogHelper.Instance.writeLog("拦截-留言-"+messge);
                        if (messge.Contains("用户请求接口次数达到限流告警"))
                        {
                            logHelp.LogHelper.Instance.writeLog("拦截-留言-用户请求接口次数达到限流告警" + messge+" token="+ MemberInfo.Instance.token);
                        }
                    }
                    StoParams.Instance.interResMsg = "留言失败-" + siteBean.siteName+" "+ msgStr;
                }
            }
            catch(Exception ex)
            {

            }
            return ret;
        }

      

        public void stopThread()
        {
            try
            {
                ArrayList arListT = new ArrayList();
                ResultBean resultBean = new ResultBean();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    /*if (totalQueryCount > 0)
                    {
                        resultBean.countTime = totalQueryCount;

                        updateQueryCount(resultBean);
                    }*/
                    fThreadDep.Abort();
                    if (swb != null)
                    {
                        swb.Close();
                    }

                }

    
            }
            catch (Exception ex)
            {

            }
        }


        private void initLog()
        {
            try
            {
                string dir = System.Environment.CurrentDirectory;
                bFile = new FileStream(dir + "\\error.txt", FileMode.Create);
                if (swb == null)
                {
                    swb = new StreamWriter(bFile);
                    swb.WriteLine("begin");

                }
            }
            catch (Exception ex)
            {

            }

        }


        public void logNoRoadMapBarcodes()
        {
            try
            {
                string fileName = DateTime.Now.ToString("yyyyMMdd") + "noroad.txt";
                string logFile = System.Environment.CurrentDirectory + "\\log\\" + fileName;   
                FileStream bFile = new FileStream(logFile, FileMode.Create);
                StreamWriter swb = null;
                if (swb == null)
                {
                    swb = new StreamWriter(bFile);
                }
                foreach(DictionaryEntry de in htInterNoRoadMap)
                {
                    swb.WriteLine(de.Key.ToString()+":"+ de.Value.ToString());
                }                
                swb.Close();

            }
            catch (Exception ex)
            {

            }
        }

        public void initNoRoadMap()
        {
            try
            {
                string fileName = DateTime.Now.ToString("yyyyMMdd") + "noroad.txt";
                string logFile = System.Environment.CurrentDirectory + "\\log\\" + fileName;
                foreach (string line in File.ReadLines(logFile, EncodingType.GetType(logFile)))
                {
                    if (line.Length > 2 && line.Length < 80)
                    {
                        string[] arr = line.Split(':');
                        if(arr.Length>1)
                        {
                            htInterNoRoadMap[arr[0]] = arr[1];
                        }
                        
                    }
                }
            }
            catch(Exception ex)
            {

            }
        }


    }
}
